package com.liu.HomeWork;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 *
 * 服务端
 */
public class HomeWork03Server {
    public static void main(String[] args) throws Exception {
        //监听8888端口
        ServerSocket serverSocket = new ServerSocket(4561);
        //等待客户端连接
        Socket socket = serverSocket.accept();
        //读取 客户端发送过来的名称
        InputStream inputStream = socket.getInputStream();
        //将名称写入到字节数组中
        byte[] b = new byte[1024];
        //下载的目录
        String downLoadFileName = " ";
        //用while读取
        int len = 0;
        while ((len = inputStream.read(b)) != -1) {
            downLoadFileName += (new String(b, 0, len));
        }
        System.out.println("接收到客户端的的下载名称" + downLoadFileName);

        //服务器上有两个 高山流水和无名
        //用户下载的是高山流水则返回，如果没有则返回无名
        String resFileName = "";
        if(downLoadFileName.equals("高山流水")) {
            resFileName = "D:\\java_code\\practice-of-network-protocol\\chapter21\\src\\高山流水.mp3";
        }else {
            resFileName = "D:\\java_code\\practice-of-network-protocol\\chapter21\\src\\无名.mp3";
        }
        //创建一个输入流，读取文件
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(resFileName));
        //使用工具类，读取文件到一个字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //得到Socket关联的输出流
        BufferedOutputStream bos= new BufferedOutputStream(socket.getOutputStream());
        bos.write(bytes);
        socket.shutdownOutput();
        //关闭资源
        bis.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
        System.out.println("服务端退出");

    }
}
